package com.example.mcdonaldapplication.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.navigation.NavArgument
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.mcdonaldapplication.R
import com.example.mcdonaldapplication.activity.BuyGoodsActivity
import com.example.mcdonaldapplication.activity.MapActivity
import com.example.mcdonaldapplication.databinding.FragmentShopBinding
import com.example.mcdonaldapplication.info.BannerImageBean
import com.example.mcdonaldapplication.info.GoodsInfo
import com.example.mcdonaldapplication.info.ServerIP
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

class ShopFragment : Fragment() {

    private val hotGoodsList = ArrayList<GoodsInfo>()
    private var _binding: FragmentShopBinding? = null
    private val binding get() = _binding!!
    private val serverIp = ServerIP.getIp()
    private val choicenessGoodsList = ArrayList<GoodsInfo>()
    private var uid = -1

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentShopBinding.inflate(inflater, container, false)
        // Inflate the layout for this fragment

        binding.cc1.setOnClickListener {
            if(uid == -1){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_loginActivity)
            }
            else {
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_integralExchangeActivity)
            }
        }
        binding.cc2.setOnClickListener {
            if(uid == -1){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_loginActivity)
            }
            else {
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_integralExchangeActivity)
            }
        }

        val banner: Banner<BannerImageBean, BannerImageAdapter<BannerImageBean>> = binding.banner as Banner<BannerImageBean, BannerImageAdapter<BannerImageBean>>
        banner.setAdapter(object: BannerImageAdapter<BannerImageBean>(BannerImageBean.testData2) {
            override fun onBindView(holder: BannerImageHolder, data: BannerImageBean, position: Int, size: Int) {
                //图片加载自己实现
                Glide.with(holder.itemView)
                    .load(data.imageRes)
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(30)))
                    .into(holder.imageView) }
        }).addBannerLifecycleObserver(this).indicator = CircleIndicator(this.context)

        getUser()
        runBlocking {
            getGoods()
            delay(500)
        }

//        val layoutManager2 = LinearLayoutManager(this.context)
        val layoutManager2 = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        binding.choicenessRecyclerView.layoutManager = layoutManager2
        Log.d("choicenessGoodsList",choicenessGoodsList.toString())
        val adapter2 = choicenessAdapter(choicenessGoodsList)
        binding.choicenessRecyclerView.adapter = adapter2

        binding.image1.setOnClickListener {
            if(uid == -1){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_loginActivity)
            }
            else{
                val intent = Intent(context,BuyGoodsActivity::class.java)
                intent.putExtra("gid",5)
                startActivity(intent)
            }
        }
        binding.image2.setOnClickListener {
            if(uid == -1){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_loginActivity)
            }
            else {
                val intent = Intent(context, BuyGoodsActivity::class.java)
                intent.putExtra("gid", 6)
                startActivity(intent)
            }
        }
        binding.image3.setOnClickListener {
            if(uid == -1){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_loginActivity)
            }
            else {
                val intent = Intent(context, BuyGoodsActivity::class.java)
                intent.putExtra("gid", 7)
                startActivity(intent)
            }
        }
        binding.image4.setOnClickListener {
            if(uid == -1){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_shop_to_loginActivity)
            }
            else {
                val intent = Intent(context, BuyGoodsActivity::class.java)
                intent.putExtra("gid", 8)
                startActivity(intent)
            }
        }
        return binding.root
    }

    inner class choicenessAdapter(val choicenessGoodsList: List<GoodsInfo>): RecyclerView.Adapter<choicenessAdapter.ViewHolder>(){
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
            val goods_name: TextView = view.findViewById(R.id.name)
            val price: TextView = view.findViewById(R.id.cgood_price)
            val img: ImageView = view.findViewById(R.id.choiceness_photo)
            val add: ImageView = view.findViewById(R.id.imageView7)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.goods_choiceness_item,parent, false)

            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val goods = choicenessGoodsList[position]
            holder.goods_name.text = goods.name
            holder.img.drawable.level = goods.gid
            holder.price.text = goods.price
            Log.d("Shop",goods.name)
            holder.itemView.setOnClickListener {
                if(uid == -1){
                    val navController = findNavController()
                    navController.navigate(R.id.action_navigation_shop_to_loginActivity)
                }
                else {
                    val intent = Intent(context, BuyGoodsActivity::class.java)
                    intent.putExtra("gid", goods.gid)
                    intent.putExtra("name", goods.name)
                    intent.putExtra("content", goods.content)
                    intent.putExtra("price", goods.price)
//                intent.putExtra("img",goods.img)
                    startActivity(intent)
                }
            }
        }

        override fun getItemCount(): Int {
            return choicenessGoodsList.size
        }
    }

    private fun getUser(){
        val prefs = requireActivity().getSharedPreferences("user", Context.MODE_PRIVATE)
        uid = prefs.getInt("uid", -1)
    }

    private fun getGoods(){
        thread {
            val formBody: FormBody = FormBody.Builder()
                .add("good_type", "5")
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIp}/goods/queryByGoodType")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            Log.d("responseData",responseData)
            parseJsonChoicenessGoods(responseData)
        }
    }

    private fun parseJsonChoicenessGoods(json: String){
        val jsonObject = JSONObject(json)
        val data = jsonObject.getJSONArray("data")

//        Log.d("goods",goods.toString())
        for(i in 0 until data.length()){
            Log.d("good", data.get(i).toString())
            val good: JSONObject = data.get(i) as JSONObject
            val gid = good.optInt("gid")
            val price = good.optString("price")
            val content = good.optString("content")
            val name = good.optString("name")
            val type = good.optInt("type")
            val num = good.optInt("num")
            val tickets = good.optInt("tickets")
            val img = good.optString("img")
            val goodType = good.optInt("goodType")
            choicenessGoodsList.add(GoodsInfo(gid,price,content,name,type,num,tickets,img,goodType))
        }
    }

}